﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using Urs.Admin.Infrastructure;
using Urs.Admin.Models.Stores;
using Urs.Core;
using Urs.Core.Caching;
using Urs.Data.Domain.Stores;
using Urs.Data.Domain.Configuration;
using Urs.Services.Stores;
using Urs.Services.Users;
using Urs.Services.ExportImport;
using Urs.Services.Localization;
using Urs.Services.Logging;
using Urs.Services.Media;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Framework.Extensions;
using Urs.Framework.Kendoui;
using Urs.Admin.Models.Common;

namespace Urs.Admin.Controllers
{
    [AdminAuthorize]
    public partial class CategoryController : BaseAdminController
    {
        #region Fields

        private readonly ICategoryService _categoryService;
        private readonly IBrandService _brandService;
        private readonly IGoodsService _goodsService;
        private readonly IUserService _userService;
        private readonly IPictureService _pictureService;
        private readonly ILocalizationService _localizationService;
        private readonly IPermissionService _permissionService;
        private readonly IExportManager _exportManager;
        private readonly IWorkContext _workContext;
        private readonly IActivityLogService _activityLogService;
        private readonly AdminAreaSettings _adminAreaSettings;
        private readonly StoreSettings _storeSettings;
        private readonly ICacheManager _cacheManager;

        #endregion

        #region Constructors

        public CategoryController(ICategoryService categoryService,
            IBrandService brandService, IGoodsService goodsService,
            IUserService userService, IPictureService pictureService,
            ILocalizationService localizationService,
             IPermissionService permissionService,
            IExportManager exportManager, IWorkContext workContext,
            IActivityLogService activityLogService, AdminAreaSettings adminAreaSettings,
            StoreSettings storeSettings, ICacheManager cacheManager)
        {
            this._categoryService = categoryService;
            this._brandService = brandService;
            this._goodsService = goodsService;
            this._userService = userService;
            this._pictureService = pictureService;
            this._localizationService = localizationService;
            this._permissionService = permissionService;
            this._exportManager = exportManager;
            this._workContext = workContext;
            this._activityLogService = activityLogService;
            this._adminAreaSettings = adminAreaSettings;
            this._storeSettings = storeSettings;
            this._cacheManager = cacheManager;
        }

        #endregion

        #region Utilities

        [NonAction]
        protected virtual void PrepareAllCategoriesModel(CategoryModel model)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            model.ParentCategories.Add(new SelectListItem
            {
                Text = "--请选择--",
                Value = "0"
            });

            var categories = SelectListHelper.GetCategoryList(_categoryService, _cacheManager, true);
            foreach (var c in categories)
                model.ParentCategories.Add(c);
        }

        #endregion

        #region List / Create / Edit / Delete

        public IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return HttpUnauthorized();

            var model = new CategoryListModel();
            return View(model);
        }

        [HttpPost]
        public IActionResult ListJson(PageRequest command, CategoryListModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return HttpUnauthorized();

            var categories = _categoryService.GetAllCategories(model.SearchCategoryName,
                command.Page - 1, command.Limit, true);
            var result = new ResponseResult
            {
                data = categories.Select(x =>
                {
                    var categoryModel = x.ToModel<CategoryModel>();
                    categoryModel.Breadcrumb = x.GetCategoryBreadCrumb(_categoryService);
                    return categoryModel;
                }),
                count = categories.TotalCount
            };
            return Json(result);
        }

        //ajax
        public IActionResult AllCategories(string text, int selectedId)
        {
            var categories = _categoryService.GetAllCategories(showHidden: true);
            categories.Insert(0, new Category { Name = "[None]", Id = 0 });
            var selectList = new List<SelectListItem>();
            foreach (var c in categories)
                selectList.Add(new SelectListItem()
                {
                    Value = c.Id.ToString(),
                    Text = c.GetCategoryBreadCrumb(_categoryService),
                    Selected = c.Id == selectedId
                });
            return Json(selectList);
        }

        public IActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return HttpUnauthorized();
            var model = new CategoryModel();
            var category = _categoryService.GetCategoryById(id);
            if (category == null || category.Deleted)
            {
                return View(model);
            }
            else
            {
                model = category.ToModel<CategoryModel>();
                PrepareAllCategoriesModel(model);
            }
            return View(model);
        }
        [HttpPost]
        public IActionResult Edit(CategoryModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return HttpUnauthorized();
            var category = _categoryService.GetCategoryById(model.Id);
            if (category == null || category.Deleted)
            {
                category = model.ToEntity<Category>();
                category.CreateTime = DateTime.Now;
                category.UpdateTime = DateTime.Now;
                _categoryService.InsertCategory(category);
                //activity log
                _activityLogService.InsertActivity("AddNewCategory", _localizationService.GetResource("ActivityLog.AddNewCategory"), category.Name);
            }
            else
            {
                if (ModelState.IsValid)
                {
                    int prevPictureId = category.PictureId;
                    category = model.ToEntity(category);
                    category.UpdateTime = DateTime.Now;
                    _categoryService.UpdateCategory(category);
                    //delete an old picture (if deleted or updated)
                    if (prevPictureId > 0 && prevPictureId != category.PictureId)
                    {
                        var prevPicture = _pictureService.GetPictureById(prevPictureId);
                        if (prevPicture != null)
                            _pictureService.DeletePicture(prevPicture);
                    }

                    //activity log
                    _activityLogService.InsertActivity("EditCategory", _localizationService.GetResource("ActivityLog.EditCategory"), category.Name);
                }
            }
            return Json(new { success = 1 });
        }

        [HttpPost]
        public IActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return HttpUnauthorized();

            var category = _categoryService.GetCategoryById(id);
            if (category == null)
                //No category found with the specified id
                return RedirectToAction("List");

            _categoryService.DeleteCategory(category);

            //activity log
            _activityLogService.InsertActivity("DeleteCategory", _localizationService.GetResource("ActivityLog.DeleteCategory"), category.Name);

            return Json(new { success = 1 });
        }

        [HttpPost]
        public IActionResult Published(CheckboxModel checkbox)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return HttpUnauthorized();

            var category = _categoryService.GetCategoryById(checkbox.Id);
            if (category == null)
                return Json(new { error = 1 });

            if (checkbox.Checked)
                category.Published = true;
            else
                category.Published = false;
            _categoryService.UpdateCategory(category);

            return Json(new { success = 1 });
        }

        [HttpPost]
        public IActionResult ShowOn(CheckboxModel checkbox)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return HttpUnauthorized();

            var category = _categoryService.GetCategoryById(checkbox.Id);
            if (category == null)
                return Json(new { error = 1 });

            if (checkbox.Checked)
                category.ShowOnHomePage = true;
            else
                category.ShowOnHomePage = false;
            _categoryService.UpdateCategory(category);

            return Json(new { success = 1 });
        }

        #endregion

    }
}
